import { Service } from 'egg';
import { Op } from 'sequelize';
import { v4 as uuidv4 } from 'uuid';
import { put } from '../util/ossFile';
import RoleEnum from '../util/roleEnum';
import areas from '../util/area';
import { Result } from '../util/result';
import MsgEnum from '../util/msgEnum';
export default class Financial extends Service {
  public async getOrganizationChart() {
    const { ctx } = this;
    const type = await ctx.model.OrganizationType.findAll();
    const typeResult = Array(0);
    for (let i = 0; i < type.length; i++) {
      const nums = await ctx.model.Organization.findAndCountAll({
        where: { fk_type: type[i].uuid },
      });
      typeResult.push(nums.count);
    }
    const typeName = type.map(v => {
      return v.name;
    });
    // console.log("typeResult",typeResult);
    const invest = await ctx.model.InvestmentDirection.findAll();
    const investResult = Array(0);
    for (let i = 0; i < invest.length; i++) {
      const nums = await ctx.model.MergeOrganizationInvestment.findAndCountAll({
        where: { investment_id: invest[i].id },
      });
      investResult.push(nums.count);
    }
    const investName = invest.map(v => {
      return v.name;
    });
    return [
      { typeName, typeResult },
      { investName, investResult },
    ];
  }

  public async showSelectList() {
    const resultsType = await this.ctx.model.OrganizationType.findAll();
    const resultsInvest = await this.ctx.model.InvestmentDirection.findAll();
    return {
      type: resultsType,
      invest: resultsInvest,
    };
  }

  public async check(financialCode) {
    const { ctx } = this;

    const exist = await ctx.model.Organization.findAll({
      where: { code: financialCode },
    });
    if (exist.length === 0) {
      return { state: false };
    }

    return { state: true };

  }

  public async showFinancialList(
    page: string,
    address: string,
    type: string,
    name: string
  ) {
    const results = await this.ctx.model.Organization.findAndCountAll({
      include: [
        { model: this.ctx.model.InvestmentDirection },
        { model: this.ctx.model.OrganizationType },
      ],
      distinct: true,
      where: {
        name: { [Op.like]: `%${name}%` },
        address: { [Op.like]: `%${address}%` },
        fk_type: { [Op.like]: `%${type}%` },
      },

      offset: Number((parseInt(page) - 1) * 10),
      limit: 10, // 假设一页展示10项
    });
    return {
      count: results.count,
      projectDataSource: results.rows,
    };
  }

  public async getFinancialMap() {
    return await this.ctx.model.Organization.findAll({ attributes: ['address'] });
  }

  public async getMapsw() {
    const mainData = await this.ctx.model.Organization.findAll({
      attributes: ['address'],
    });
    const data: any = {};
    mainData.forEach((v: { address: string }) => {
      const add = v.address?.split(';')[1];
      if (!data.hasOwnProperty(add)) {
        data[add] = 1;
      } else {
        data[add]++;
      }
    });
    let dataw = 'lng,lat,name,v\n';
    for (const name in data) {
      if (data.hasOwnProperty(name)) {
        if (areas[name] && name !== undefined && name !== 'undefined') {
          console.log(name);

          dataw += areas[name].join(',') + ',' + name + ',' + data[name] + '\n';
        } else {
          dataw += '\n';
        }
      }
    }
    return dataw;
  }


  public async updateFinancial(
    id: string,
    financialType,
    financialAddress,
    financialName,
    creatTime: string,
    invest: string,
    contactPerson: string,
    contactTel: string,
    contactEmail: string,
    description: string,
    updateTime,
    filler
  ) {
    const typeuuid = await this.ctx.model.OrganizationType.findOne({
      where: {
        name: financialType,
      },
    });
    const tags = await this.ctx.model.InvestmentDirection.findAll({
      where: { name: invest },
    });
    this.ctx.model.Organization.update(
      {
        fk_type: typeuuid.uuid,
        name: financialName,
        address: financialAddress,
        financialName,
        createTime: creatTime,
        contactPerson,
        contactTel,
        contactEmail,
        description,
        updateTime,
        filler,
      },
      {
        where: {
          id,
        },
      }
    );

    const results = await this.ctx.model.Organization.findOne({
      where: { id },
    });

    await results.setInvestment_directions(tags);
    return {
      state: results ? 'true' : 'false',
    };
  }

  public async createFinancial(
    financialName,
    financialCode,
    financialAddress,
    financialType,
    createTime,
    invest,
    contactPerson,
    contactEmail,
    contactTel,
    updateTime,
    filler,
    description,
    r
  ) {
    const UUID = uuidv4();
    const typeuuid = await this.ctx.model.OrganizationType.findOne({
      where: {
        name: financialType,
      },
    });

    const results = await this.ctx.model.Organization.create({
      uuid: UUID,
      name: financialName,
      address: financialAddress,
      fk_type: typeuuid.uuid,
      createTime,
      contactPerson,
      contactTel,
      contactEmail,
      description,
      updateTime,
      filler,
      code: financialCode,
    });

    const tags = await this.ctx.model.InvestmentDirection.findAll({
      where: { name: invest.split(',') },
    });

    await results.setInvestment_directions(tags);
    console.log(results);
    if (r.file_name !== 'null.xlsx') {
      await put(RoleEnum.ORGANIZATION, results.dataValues.id, r);
    }
    return {
      state: 'true',
    };
  }

  public async createUploadFinancial(
    financialName,
    financialCode,
    financialAddress,
    financialType,
    createTime,
    invest,
    contactPerson,
    contactEmail,
    contactTel,
    description,
    username
  ) {
    const exist = await this.ctx.model.Organization.findAll({
      where: {
        code: financialCode,
      },
    });
    if (exist.length === 0) {
      const UUID = uuidv4();
      const typeuuid = await this.ctx.model.OrganizationType.findOne({
        where: {
          name: financialType,
        },
      });

      const results = await this.ctx.model.Organization.create({
        uuid: UUID,
        code: financialCode,
        name: financialName,
        address: financialAddress,
        fk_type: typeuuid.uuid,
        createTime:
          Number(createTime) + '' !== NaN + ''
            ? new Date((createTime - 25569) * 24 * 60 * 60 * 1000)
            : createTime,
        contactPerson,
        contactTel,
        contactEmail,
        description,
        updateTime: new Date(),
        filler: username,
      });

      const tags = await this.ctx.model.InvestmentDirection.findAll({
        where: { name: invest.split(';') },
      });

      await results.setInvestment_directions(tags);
      return {
        state: 'true',
      };
    }
    return {
      state: 'false',
    };

  }

  public async deleteFinancial(key: string) {
    let transaction;
    try {
      transaction = await this.ctx.model.transaction();
      await this.ctx.model.MergeOrganizationInvestment.destroy({
        where: { organization_id: key },
        transaction
      });
      await this.ctx.model.MergeProductOrganization.destroy({
        where: { organization_id: key },
        transaction
      });
      const result = await this.ctx.model.Organization.destroy({
        where: { id: key },
        transaction
      });
      await transaction.commit();
      return new Result({ result }, MsgEnum.UPLOAD_SUCCESS);
    } catch (e) {
      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }
}
